package com.movecar.ui;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.movecar.R;
import com.movecar.dialog.CustomDialog;
import com.movecar.listview.MyListView;
import com.movecar.model.CloudBeansBean;
import com.movecar.model.ClubBean;
import com.movecar.model.GroupBean;
import com.movecar.model.Pictures;
import com.movecar.model.RecommendClubBean;
import com.movecar.model.RecommendClubTheemeBean;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.DataStore;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.RequestResultCallback;
import com.movecar.utils.imageloader.Constants;
import com.movecar.widget.CustomProgressDialog;
import com.movecar.widget.MyGridView;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 推荐俱乐部详情
 * 
 * @author Zhao.JQ
 * 
 */
public class RecommendClubDetailActivity extends Activity implements OnClickListener {

	private TextView club_name, club_time, owner_phone;
	private ArrayList<Pictures> picturesData = null;
	private MyGridView mGridView;
	private String mSectionId = "";
	private ImageView clubImg;
	private DataAdapter adapter;
	private ImageLoader imageLoader = null;
	private CustomProgressDialog progressDialog = null;
	private RecommendClubBean mRecommendClubBean;
	private MyListView mListView;
	private LinearLayout main_linear;
	private Button right;
	private CloudBeansBean mCloudBeansBean = null;
	private boolean isClicked = false;
	private int position;
	private List<RecommendClubTheemeBean> themeList;

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.recommend_club_detail);
		position = getIntent().getIntExtra("position", 0);
		initView();
	}

	private void initView() {
		imageLoader = ImageLoader.getInstance();
		// imageLoader.init(Constants.imageLoaderConfiguration(this));
		stopProgressDialog();
		findViewById(R.id.img_layout).setOnClickListener(this);
		// message_board = (Button) findViewById(R.id.message_board);
		Button btn_left = (Button) findViewById(R.id.btn_left);
		btn_left.setVisibility(View.VISIBLE);
		btn_left.setOnClickListener(this);
		right = (Button) findViewById(R.id.btn_right);
		main_linear = (LinearLayout) findViewById(R.id.main_linear);

		clubImg = (ImageView) findViewById(R.id.club_img);
		mGridView = (MyGridView) findViewById(R.id.mGridView);
		club_name = (TextView) findViewById(R.id.club_name);
		owner_phone = (TextView) findViewById(R.id.club_owener_phone);
		owner_phone.setOnClickListener(this);
		club_time = (TextView) findViewById(R.id.club_time);
		mListView = (MyListView) findViewById(R.id.mListView);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText("详情");
		if (this.getIntent() != null) {
			mSectionId = getIntent().getStringExtra("sectionId");

			startProgressDialog();
			getRecommendClubDetail();

		}
		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

				if (picturesData != null && picturesData.size() > 0) {
					Intent intent = new Intent(RecommendClubDetailActivity.this, ClubPhotoActivity.class);
					intent.putExtra("Pictures", picturesData);
					intent.putExtra("currentId", arg2);
					startActivity(intent);
				}

			}
		});
	}

	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.btn_left:
			if (isClicked) {
				Intent i = new Intent();
				i.putExtra("position", position);
				setResult(RESULT_OK, i);
			}
			isClicked = false;
			finish();

			break;
		case R.id.img_layout:
			if (picturesData != null && picturesData.size() > 0) {
				Intent intent = new Intent();
				intent.putExtra("Pictures", picturesData);
				startActivity(intent);
			}
			break;

		case R.id.club_owener_phone:
			if (!owner_phone.getText().toString().equals("未上传")) {
				CustomDialog.Builder customBuilder = new CustomDialog.Builder(RecommendClubDetailActivity.this);
				ImageView img = new ImageView(RecommendClubDetailActivity.this);
				img.setImageResource(R.drawable.ic_launcher);
				customBuilder.setImgIcon(img).setMessage("是否确认打电话?")

				.setPositiveButton("打电话", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent call = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
								+ owner_phone.getText().toString())); // 创建一个意图
						RecommendClubDetailActivity.this.startActivity(call);// 开始意图(及拨打电话)
						dialog.dismiss();

					}
				}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

						dialog.dismiss();

					}
				});
				customBuilder.create().show();
			}

			break;
		case R.id.look_all_relative:
			Intent next = new Intent(this, GroupActivity.class);
			next.putExtra("sectionId", mSectionId);
			// next.putExtra("club_data", true);
			startActivity(next);
			break;
		case R.id.btn_right:
			isClicked = true;
			startProgressDialog();
			followJsonData(mSectionId);
			getRecommendClubDetail();
			break;
		default:
			break;
		}

	}

	@SuppressWarnings("unchecked")
	private void getRecommendClubDetail() {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "queryRecommendSectionNew1")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("sectionId", mSectionId));

		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;

				Gson gson = new Gson();
				try {
					mRecommendClubBean = gson.fromJson(result, RecommendClubBean.class);
				} catch (Exception e) {
					return;
				}
				if (null != mRecommendClubBean) {
					main_linear.setVisibility(View.VISIBLE);
					club_name.setText("名称：" + mRecommendClubBean.getSectionName());
					owner_phone.setText("联系方式："
							+ (TextUtils.isEmpty(mRecommendClubBean.getPhone()) ? "未上传" : mRecommendClubBean.getPhone()));
					club_time.setText("地址：" + mRecommendClubBean.getAddress());
					// description.setText(mRecommendClubBean.getContent());

					clubImg.setVisibility(View.VISIBLE);

					imageLoader.displayImage(AppConfig.HOST + mRecommendClubBean.getLogo(), clubImg);

					if (mRecommendClubBean.getList().size() > 0) {
						themeList = mRecommendClubBean.getList();
						mListView.setVisibility(View.VISIBLE);
						adapter = new DataAdapter(RecommendClubDetailActivity.this, themeList);
						mListView.setAdapter(adapter);

					}
				} else {
					Alert.error(RecommendClubDetailActivity.this, "系统异常");
				}

			}

			@Override
			public void onFail(String exception) {

				stopProgressDialog();
				Alert.error(RecommendClubDetailActivity.this, "与服务器连接失败，请检查网络");

			}
		}, ClubBean.class, AppConfig.CLUB).execute(params);
	}

	/**
	 * 关注
	 * 
	 * @param sectionId
	 */
	@SuppressWarnings("unchecked")
	private void followJsonData(String sectionId) {

		List<NameValuePair> params = new ArrayList<NameValuePair>(); // 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "specialFocusNew1")); // 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("sectionId", sectionId));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {
				stopProgressDialog();
				String result = (String) object;
				Gson gson = new Gson();
				try {
					mCloudBeansBean = gson.fromJson(result, CloudBeansBean.class);
				} catch (Exception e) {
					return;
				}
				if ("0".equals(mCloudBeansBean.getResultCode())) {

				} else {
					stopProgressDialog();
					Alert.info(RecommendClubDetailActivity.this, result);
				}
			}

			@Override
			public void onFail(String exception) {

				Alert.error(RecommendClubDetailActivity.this,"与服务器连接失败，请检查网络");

			}
		}, GroupBean.class, AppConfig.CLUB).execute(params);
	}

	class DataAdapter extends BaseAdapter {

		Activity activity;
		private LayoutInflater inflater;
		private ViewHolder viewHolder = null;

		List<RecommendClubTheemeBean> themeList;

		DataAdapter(Activity activity, List<RecommendClubTheemeBean> themeList) {

			this.activity = activity;
			this.themeList = themeList;
			inflater = LayoutInflater.from(activity);

		}

		@Override
		public int getCount() {

			return themeList.size();
		}

		@Override
		public Object getItem(int arg0) {

			return themeList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {

			return arg0;
		}

		@Override
		public View getView(final int position, View view, ViewGroup arg2) {

			if (view == null) {
				viewHolder = new ViewHolder();
				view = inflater.inflate(R.layout.recommend_club_detail_item, null);

				viewHolder.club_img = (ImageView) view.findViewById(R.id.club_img);
				viewHolder.share_num = (TextView) view.findViewById(R.id.share_num);

				view.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) view.getTag();
			}

			imageLoader.displayImage(AppConfig.HOST + themeList.get(position).getPmLogo(), viewHolder.club_img,
					Constants.image_display_options, AppConfig.animateListener);
			viewHolder.share_num.setText(themeList.get(position).getPmCount());
			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(RecommendClubDetailActivity.this, NewHomeActivity.class);
					intent.putExtra("sectionId", mSectionId);
					intent.putExtra("pmId", themeList.get(position).getPmId());
					startActivity(intent);

				}
			});
			return view;
		}

		class ViewHolder {

			ImageView club_img;
			TextView share_num;
		}
	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	public boolean dispatchKeyEvent(KeyEvent event) {

		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getRepeatCount() == 0) {

			if (isClicked) {
				Intent i = new Intent();
				i.putExtra("position", position);
				setResult(RESULT_OK, i);
			}
			isClicked = false;
			finish();
			return false;
		} else {
			return super.dispatchKeyEvent(event);
		}
	}
}
